import React, { Component } from "react"
import { withRouter } from "react-router"
import styles from './register.less'
import CInput from '@/components/input'
import { register } from '@/services'
import { forgetPwd } from '@/services'
import Toast from '@/utils/toast';

class ForgetPwd extends Component {

  constructor(props){
    super(props);
    this.state = {
      phone: '',
      password: '',
      repassword: '',
    }
  }

  onChange = (e) => {
    this.setState({
      [e.target.name] : e.target.value
    })
  }

  handleSubmit = async () => {
    try {
      const { phone, password, repassword } = this.state;
      if(!(phone.length == 11 && (/^[1][0-9]{10}$/.test(phone)))){
        return Toast.error('请输入正确的手机号')
      }
      if(!(password && repassword)){
        return Toast.error('请输入密码')
      }
      if(password!==repassword){
        return Toast.error('两次密码输入不一致')
      }
      const data = await forgetPwd({ userName: phone, password: password, confirmPassword: repassword })
      if(data.code==200){
        Toast.success(data.data);
        this.props.history.replace('/login')
      }
    } catch (error) {
      console.log(error)
    }
  }
  
  render(){
    return (
      <div className={styles.wrapper}>
        <div className={styles.title}>
          <img onClick={()=>{ this.props.history.go('-1') }} className={styles.title_back} src={require('../assets/img/login/back.png')} /> 
          <div>重设密码</div>
        </div>
        <CInput 
          img={require('../assets/img/login/phone.png')} 
          onChange={this.onChange}
          type="tel"
          placeholder="请输入手机号码"
          name="phone"
          value={this.state.phone}
        />
        <CInput 
          img={require('../assets/img/login/pwd.png')} 
          onChange={this.onChange}
          type="password"
          placeholder="请设置密码"
          name="password"
          value={this.state.password}
        />
        <CInput 
          img={require('../assets/img/login/pwd.png')} 
          onChange={this.onChange}
          type="password"
          placeholder="请设置密码"
          name="repassword"
          value={this.state.repassword}
        />
        <div className={styles.submit} onClick={this.handleSubmit}>
          确认
        </div>
      </div>
    )
  }
}

export default withRouter(ForgetPwd)